<template>
  <div class="notepad-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Edit /></el-icon>
          <div class="header-text">
            <h2>记事本</h2>
            <p>记录你的想法和重要信息</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="handleNewNote">
            <el-icon><Plus /></el-icon>
            新建笔记
          </el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20">
      <!-- 左侧笔记列表 -->
      <el-col :span="6">
        <el-card shadow="never" class="list-card">
          <div class="list-header">
            <el-input
              v-model="searchText"
              placeholder="搜索笔记..."
              clearable
              size="small"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="note-list">
            <div
              v-for="note in filteredNotes"
              :key="note.id"
              class="note-item"
              :class="{ active: selectedNote?.id === note.id }"
              @click="selectNote(note)"
            >
              <div class="note-title">{{ note.title }}</div>
              <div class="note-preview">{{ note.preview }}</div>
              <div class="note-meta">
                <span class="note-time">{{ note.updateTime }}</span>
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click.stop="handleDelete(note)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            <el-empty v-if="filteredNotes.length === 0" description="暂无笔记" :image-size="80" />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧编辑区 -->
      <el-col :span="18">
        <el-card shadow="never" class="editor-card">
          <div v-if="selectedNote" class="editor-wrapper">
            <div class="editor-header">
              <el-input
                v-model="selectedNote.title"
                placeholder="请输入标题"
                class="title-input"
                @blur="handleSave"
              />
              <div class="editor-actions">
                <el-button @click="handleSave">
                  <el-icon><DocumentChecked /></el-icon>
                  保存
                </el-button>
                <el-button @click="handleExport">
                  <el-icon><Download /></el-icon>
                  导出
                </el-button>
              </div>
            </div>
            <div class="editor-content">
              <div class="rich-editor-wrapper">
                <Toolbar
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  mode="default"
                  class="editor-toolbar"
                />
                <Editor
                  v-model="selectedNote.content"
                  :defaultConfig="editorConfig"
                  mode="default"
                  class="editor-content-area"
                  @onCreated="handleEditorCreated"
                  @onChange="handleEditorChange"
                />
              </div>
            </div>
            <div class="editor-footer">
              <div class="meta-info">
                <span>创建时间：{{ selectedNote.createTime }}</span>
                <span>更新时间：{{ selectedNote.updateTime }}</span>
              </div>
            </div>
          </div>
          <div v-else class="empty-editor">
            <el-icon :size="80" color="#C0C4CC"><Edit /></el-icon>
            <p>选择一个笔记开始编辑，或创建新笔记</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新建笔记对话框 -->
    <el-dialog v-model="showNewNoteDialog" title="新建笔记" width="500px">
      <el-form :model="newNoteForm" label-width="80px">
        <el-form-item label="笔记标题">
          <div class="input-with-voice">
            <el-input v-model="newNoteForm.title" placeholder="请输入笔记标题" />
            <div
              class="voice-icon"
              @click="handleTitleVoiceClick"
              :class="{ 'recording': titleVoiceRecording, 'disabled': !titleVoiceSupported }"
              :title="titleVoiceSupported ? (titleVoiceRecording ? '正在录音中...' : '点击开始语音输入标题') : '浏览器不支持语音识别'"
            >
              <el-icon :size="18">
                <Microphone />
              </el-icon>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showNewNoteDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateNote">确定</el-button>
      </template>
    </el-dialog>

    <!-- 语音输入组件 -->
    <VoiceInput
      mode="float"
      :show-overlay="true"
      label="正在语音输入标题..."
      tip-text="说出笔记标题，点击停止按钮完成输入"
      placeholder="请说出笔记标题"
      @transcript="handleTitleVoiceTranscript"
      @start="handleTitleVoiceStart"
      @stop="handleTitleVoiceStop"
      ref="titleVoiceInputRef"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, shallowRef, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Edit, Plus, Search, Delete, DocumentChecked, Download, Microphone
} from '@element-plus/icons-vue'
import { keyUser, valueUser } from '@/api/data'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import VoiceInput from '@/components/common/VoiceInput.vue'

// 状态
const searchText = ref('')
const selectedNote = ref(null)
const showNewNoteDialog = ref(false)

// 表单
const newNoteForm = reactive({
  title: ''
})

// 语音输入相关
const titleVoiceInputRef = ref(null)
const titleVoiceSupported = ref(false)
const titleVoiceRecording = ref(false)

// 监听语音输入组件是否支持语音
watch(() => titleVoiceInputRef.value?.isVoiceSupported, (val) => {
  if (val !== undefined) {
    titleVoiceSupported.value = val
  }
})

// 监听语音输入状态
watch(() => titleVoiceInputRef.value?.isRecording, (val) => {
  if (val !== undefined) {
    titleVoiceRecording.value = val
  }
})

// 笔记数据
const notes = ref([])

// 富文本编辑器
const editorRef = shallowRef()
const toolbarConfig = {
  // 简洁的工具栏配置，只包含常用功能
  excludeKeys: [
    'group-video',
    'group-more-style',
    'insertTable',
    'codeBlock',
    'divider',
    'fullScreen'
  ]
}
const editorConfig = {
  placeholder: '开始记录你的想法...',
  height: 'auto', // 自动高度，由容器控制
  MENU_CONF: {}
}

// 编辑器创建
const handleEditorCreated = (editor) => {
  editorRef.value = editor
}

// 编辑器内容改变
const handleEditorChange = () => {
  // 自动保存功能可以通过防抖处理，这里简化处理
}

// 去除 HTML 标签获取纯文本（用于预览）
const stripHtml = (html) => {
  if (!html) return ''
  const tmp = document.createElement('DIV')
  tmp.innerHTML = html
  return tmp.textContent || tmp.innerText || ''
}

// 计算属性
const filteredNotes = computed(() => {
  if (!searchText.value) return notes.value
  const keyword = searchText.value.toLowerCase()
  return notes.value.filter(note =>
    note.title.toLowerCase().includes(keyword) ||
    stripHtml(note.content || '').toLowerCase().includes(keyword)
  )
})

// 加载笔记数据
const loadNotes = async () => {
  try {
    const response = await keyUser('notepad')
    if (response && response.code === 200 && response.data) {
      let data = response.data
      if (typeof data === 'string') {
        data = JSON.parse(data)
      } else if (data.value) {
        data = JSON.parse(data.value)
      }
      if (Array.isArray(data)) {
        notes.value = data
      } else if (data.notes && Array.isArray(data.notes)) {
        notes.value = data.notes
      }
      // 计算预览文本（去除 HTML 标签）
      notes.value.forEach(note => {
        if (!note.preview) {
          const textContent = stripHtml(note.content || '')
          note.preview = textContent && textContent.length > 50
            ? textContent.substring(0, 50) + '...'
            : textContent || '无内容'
        }
      })
    }
  } catch (error) {
    console.error('加载笔记数据失败:', error)
    // 失败时使用默认数据
    if (notes.value.length === 0) {
      notes.value = []
    }
  }
}

// 保存笔记数据
const saveNotes = async () => {
  try {
    const dataToSave = notes.value.map(note => ({
      ...note,
      preview: undefined // 不保存预览，每次加载时重新计算
    }))
    await valueUser('notepad', JSON.stringify(dataToSave))
  } catch (error) {
    console.error('保存笔记数据失败:', error)
    ElMessage.error('保存笔记失败')
  }
}

// 方法
const selectNote = (note) => {
  selectedNote.value = { ...note }
  // 延迟设置编辑器内容，确保编辑器已创建
  if (editorRef.value) {
    setTimeout(() => {
      if (editorRef.value && selectedNote.value) {
        editorRef.value.setHtml(selectedNote.value.content || '')
      }
    }, 100)
  }
}

const handleNewNote = () => {
  newNoteForm.title = ''
  showNewNoteDialog.value = true
}

// 处理标题语音图标点击
const handleTitleVoiceClick = () => {
  if (!titleVoiceInputRef.value) return
  
  if (!titleVoiceSupported.value) {
    ElMessage.warning('您的浏览器不支持语音识别，请使用Chrome或Edge浏览器')
    return
  }
  
  if (titleVoiceRecording.value) {
    titleVoiceInputRef.value.stopRecording()
  } else {
    titleVoiceInputRef.value.startRecording()
  }
}

// 处理标题语音输入文本
const handleTitleVoiceTranscript = (transcript, isFinal, finalText) => {
  if (isFinal && finalText) {
    newNoteForm.title = finalText.trim()
  } else if (transcript) {
    newNoteForm.title = transcript.trim()
  }
}

// 处理标题语音开始
const handleTitleVoiceStart = () => {
  titleVoiceRecording.value = true
}

// 处理标题语音停止
const handleTitleVoiceStop = () => {
  titleVoiceRecording.value = false
}

const handleCreateNote = async () => {
  if (!newNoteForm.title.trim()) {
    ElMessage.warning('请输入笔记标题')
    return
  }
  const now = new Date().toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
  const newNote = {
    id: Date.now(),
    title: newNoteForm.title,
    content: '',
    createTime: now,
    updateTime: now,
    preview: '无内容'
  }
  notes.value.unshift(newNote)
  selectedNote.value = { ...newNote }
  showNewNoteDialog.value = false
  await saveNotes()
  ElMessage.success('创建成功')
}

const handleSave = async () => {
  if (!selectedNote.value) return
  // 获取编辑器的 HTML 内容
  if (editorRef.value) {
    selectedNote.value.content = editorRef.value.getHtml()
  }
  const index = notes.value.findIndex(note => note.id === selectedNote.value.id)
  if (index > -1) {
    selectedNote.value.updateTime = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).replace(/\//g, '-')
    // 更新预览文本（去除 HTML 标签）
    const textContent = stripHtml(selectedNote.value.content || '')
    selectedNote.value.preview = textContent && textContent.length > 50
      ? textContent.substring(0, 50) + '...'
      : textContent || '无内容'
    notes.value[index] = { ...selectedNote.value }
    await saveNotes()
    ElMessage.success('保存成功')
  }
}

const handleDelete = async (note) => {
  ElMessageBox.confirm('确定要删除该笔记吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    const index = notes.value.findIndex(n => n.id === note.id)
    if (index > -1) {
      notes.value.splice(index, 1)
      if (selectedNote.value?.id === note.id) {
        selectedNote.value = null
      }
      await saveNotes()
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

const handleExport = () => {
  if (!selectedNote.value) {
    ElMessage.warning('请先选择一个笔记')
    return
  }
  // 获取编辑器内容（如果编辑器存在）
  let content = selectedNote.value.content
  if (editorRef.value) {
    content = editorRef.value.getHtml()
  }
  // 导出为 HTML 格式或纯文本格式
  const textContent = stripHtml(content)
  const exportContent = `${selectedNote.value.title}\n\n${textContent}\n\n创建时间：${selectedNote.value.createTime}\n更新时间：${selectedNote.value.updateTime}`
  const blob = new Blob([exportContent], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `${selectedNote.value.title}.txt`
  link.click()
  URL.revokeObjectURL(url)
  ElMessage.success('导出成功')
}

// 组件挂载时加载数据
onMounted(() => {
  loadNotes()
})

// 组件销毁时清理编辑器
onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy()
  }
})

// 监听 selectedNote 变化，同步到编辑器
watch(() => selectedNote.value, (newVal) => {
  if (newVal && editorRef.value) {
    setTimeout(() => {
      if (editorRef.value && selectedNote.value) {
        editorRef.value.setHtml(selectedNote.value.content || '')
      }
    }, 100)
  }
}, { deep: true })
</script>

<style scoped>
.notepad-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.list-card {
  height: calc(100vh - 180px);
  display: flex;
  flex-direction: column;
}

.list-header {
  margin-bottom: 16px;
}

.note-list {
  flex: 1;
  overflow-y: auto;
}

.note-item {
  padding: 12px;
  border: 1px solid #EBEEF5;
  border-radius: 6px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.note-item:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
}

.note-item.active {
  border-color: #409EFF;
  background-color: #ECF5FF;
}

.note-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.note-preview {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.note-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.note-time {
  flex: 1;
}

.editor-card {
  height: calc(100vh - 180px);
  display: flex;
  flex-direction: column;
}

.editor-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #EBEEF5;
}

.title-input {
  flex: 1;
  margin-right: 16px;
}

.title-input :deep(.el-input__inner) {
  font-size: 20px;
  font-weight: 500;
  border: none;
  padding: 0;
}

.editor-actions {
  display: flex;
  gap: 10px;
}

.editor-content {
  flex: 1;
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
}

.rich-editor-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
  min-height: 0; /* 确保 flex 子元素可以缩小 */
}

.editor-toolbar {
  border-bottom: 1px solid #EBEEF5;
}

.editor-content-area {
  flex: 1;
  overflow-y: auto;
  min-height: 0; /* 确保 flex 子元素可以缩小 */
}

/* 覆盖编辑器默认高度样式 */
.editor-content-area :deep(.w-e-text-container) {
  height: 100% !important;
}

.editor-content-area :deep(.w-e-text-placeholder) {
  height: 100%;
}

.editor-content-area :deep(.w-e-scroll) {
  height: 100% !important;
}

.editor-footer {
  padding-top: 16px;
  border-top: 1px solid #EBEEF5;
}

.meta-info {
  display: flex;
  gap: 24px;
  font-size: 12px;
  color: #909399;
}

.empty-editor {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #C0C4CC;
}

.empty-editor p {
  margin-top: 16px;
  font-size: 14px;
}

/* 语音输入样式 */
.input-with-voice {
  position: relative;
  display: flex;
  align-items: center;
}

.input-with-voice :deep(.el-input) {
  flex: 1;
}

.input-with-voice :deep(.el-input__inner) {
  padding-right: 40px;
}

.voice-icon {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #909399;
  border-radius: 4px;
  transition: all 0.3s;
  z-index: 1;
}

.voice-icon:hover:not(.disabled) {
  background-color: #f0f9ff;
  color: #409EFF;
}

.voice-icon.recording {
  color: #f56c6c;
  animation: pulse 1.5s ease-in-out infinite;
}

.voice-icon.recording .el-icon {
  animation: pulse-icon 1.5s ease-in-out infinite;
}

.voice-icon.disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.voice-icon .el-icon {
  transition: all 0.3s;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
}

@keyframes pulse-icon {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}
</style>

